<template>
  <van-field
    v-bind="$attrs"
    clearable
    :value="value"
    :readonly="readonly"
    :input-align="inputAlign"
    :placeholder="$attrs.placeholder || placeholder"
    :right-icon="getRightIcon"
    @keyup.enter="handleEnter"
    @click="handleClick"
    @click-right-icon="handleRightIcon"
    @update:value="handleChange"
  >
    <template #button>
      <slot name="button" />
    </template>
  </van-field>
</template>

<script>
import { computed, getCurrentInstance, onMounted } from 'vue';
import { useDebounceFn } from '@vueuse/core';
import { common } from '@/utils';

export default {
  name: 'qt-input',

  props: {
    value: [String, Number],

    fieldName: {
      type: String,
    },

    inputAlign: {
      type: String,
      default: 'right',
    },

    isScan: {
      type: Boolean,
      default: false,
    },
  },

  setup(props, { attrs, emit }) {
    const { ctx } = getCurrentInstance();

    const placeholder = computed(() => {
      let text = '';

      if (getRightIcon !== 'arrow') {
        text = '请输入';
      } else {
        text = '请选择';
      }
      return text + attrs.label;
    });

    const getRightIcon = computed(() => {
      return props.isScan ? 'scan' : attrs['right-icon'];
    });

    const readonly = computed(() => {
      return attrs['right-icon'] === 'arrow' ? true : attrs.readonly;
    });

    onMounted(() => {
      ctx.$eventBus.$on('scan', (data, name) => {
        if (name === props.fieldName) {
          emit('input', data);
        }
      });
    });

    const handleEnter = useDebounceFn(event => {
      if (ctx.$parent?.$options.name === 'qt-form') {
        ctx.$parent.validateField([props.fieldName]);
        emit('enter', event);
      }
    }, 400);

    const handleClick = useDebounceFn(event => {
      emit('click', event);
    }, 400);

    const handleChange = value => {
      emit('update:value', value);
      emit('change', value, props.fieldName);
    };

    const handleRightIcon = () => {
      if (props.isScan) {
        common.checkPlus(() => {
          ctx.$scan.show();
          ctx.$scan.fieldName = props.fieldName;
        });
      }
    };

    return {
      placeholder,
      readonly,
      getRightIcon,
      handleEnter,
      handleChange,
      handleRightIcon,
      handleClick,
    };
  },
};
</script>
